// Learn cc.Class:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    statics: {
        _instance: null,
        _isAndroid: false,
        InterstitialAdId: 'adunit-872581b4a4a4c9949d58e7cf8e530d8f24',
        RewardedVideoAdId: ["2ajug6dv1e713h0ab4", "xhyvgew93c402340qh", "d9krbc5or3m1c4gc7e", "o3cj4374771elq088b", "6lplenlg2cd291oom2", "7nd5a9e5ekn25ej734"],
        BannerIds: ['c4fgg6e5a0al11c4om', 'lahkg87k8fjct360fg', 'yb5ejyi6p1ai814077', '9c4ski0biofajb9dso', "g0ei49jfk9583ote60", "39an2mhn91q5g31md9", "17o4mk8776el9ale5k", "jlind8526os1itipts", "3357h2c295kf5ii8g1"],
        tuiguangAdId: ["PBgAA840fLgpwuog"],

        ShareTitle: "看过许多美景——身边依然还是你",
        ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    // LIFE-CYCLE CALLBACKS:

    link() {
        require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": 1 }, function (data) {
            if (data.code === 0) {
                console.log("返回数据", data);
            }
            else {
                console.log("连接失败", data);
                return;
            };
        });
    },


    onLoad() {
        console.log('tt onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;

        if (!window.wx) {
            return;
        }

        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }

        this.craetTTRecorder();
        //...
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        this.setLogin();
        this.id = 2;
        this.scheduleOnce(this.createBannerAds, 1);
        this.scheduleOnce(this.createInterstitialAd, 10);
        //var callBackFun = this.createRewardedVideoAd(0);
        // this.scheduleOnce(callBackFun, 3);
    },


    start() {
    },

    shareAppMessage(i) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        cc.log('shareAppMessage...');

        //var maxGuanqia = cc.sys.localStorage.getItem('local_guanIndex');
        var maxGuanqia = require('GameMgr').Instance().getGuanQia();
        var Score = require('GameMgr').Instance().getLogin().maxScore;
        var Rank = parseInt(maxGuanqia / 1000) + "-" + maxGuanqia % 1000;//分享内容
        var ShareTitle1 = "";
        if (i === 1) {
            ShareTitle1 = "看过许多美景——身边依然还是你";
        } else if (i === 2) {
            // ShareTitle1 = "全服第" + +"名，不服你来试试！";
            ShareTitle1 = "高分全凭手速！我在" + Rank + "关获得" + Score + "分，你敢挑战吗？";
        } else if (i === 3) {
            ShareTitle1 = "高分全凭手速！我在" + Rank + "关获得" + Score + "分，你敢挑战吗？";
        }

        tt.shareAppMessage({
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            success() {
                console.log("分享成功");
                require('GameMgr').Instance().setDaily(5);
                require('GameMgr').onWxShow(1001);
            },
            fail(e) {
                console.log("分享失败");
            }
        });

        this.closeTime = new Date().getTime();
        this._shareTime = new Date().getTime();
        this.isShared = true;
    },

    showInterstitialAd() {
        if (!window.wx) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    },


    showRewardedVideoAd(index) {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        var self = this;
        var id = 0;
        if (index) {
            id = parseInt(index);
        }
        this.AudioCloseTime = new Date().getTime();
        //console.log("创建视频广告", index, id, this.RewardedVideoAdId, this.RewardedVideoAdId[id]);
        var videoAd = tt.createRewardedVideoAd({
            adUnitId: curMod.RewardedVideoAdId[id]
        });
        videoAd.load();
        // 显示广告
        videoAd
            .show()
            .then(() => {
                console.log("广告显示成功");
            })
            .catch(err => {
                console.log("广告组件出现问题", err);
                // 可以手动加载一次
                videoAd.load().then(() => {
                    console.log("手动加载成功");
                    // 加载成功后需要再显示广告
                    return videoAd.show();
                });
            });
        videoAd.onClose(res => {
            console.log(res);
            if (res.isEnded) {
                // 给予奖励
                require('GameMgr').Instance().ShowADrewords();
                // 正常播放结束，可以下发游戏奖励
                require('GameMgr').Instance().setDaily(2);
            }
            else {
                /*
                if (require('GameMgr').Instance().ApiType === 2) {
                    let curTime = new Date().getTime();
                    console.log("看视频时间：", curTime, self.AudioCloseTime);
                    if (curTime - self.AudioCloseTime >= 10000) {
                        require('GameMgr').Instance().ShowADrewords();
                        // 正常播放结束，可以下发游戏奖励
                        require('GameMgr').Instance().setDaily(2);
                    }
                    else {*/
                require('GameMgr').Instance().onAddExit();
                return;
            }
        });

        if (!this._rewardedVideoAd) {
            return;
        }
    },



    showBannerAd(index) {
        if (!window.wx) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            if (require('GameMgr').Instance().ApiType === 1) {
                this._bannerAds[index].show();
            }
            else if (require('GameMgr').Instance().ApiType === 2) {
                this._bannerAds[index].show();
                this._bannerAds[index].onLoad(function () {
                    this._bannerAds[index]
                        .show()
                        .then(() => {
                            console.log("底部广告显示成功");
                        })
                        .catch(err => {
                            console.log("底部广告组件出现问题", err);
                        });
                });
            }

        }
    },

    //隐藏所有广告
    hideBannerAds() {
        if (!window.wx) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    },

    createBannerAds() {
        let winSize = curMod._systemInfo; //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        var length = curMod.BannerIds.length;
        for (let i = 0; i < length; i++) {
            if (require('GameMgr').Instance().ApiType === 2) {
                var self = this;
                const { windowWidth, windowHeight } = tt.getSystemInfoSync();
                var targetBannerAdWidth = 200;
                let banner = tt.createBannerAd({
                    adUnitId: curMod.BannerIds[i],
                    adIntervals: 30,
                    style: {
                        width: targetBannerAdWidth,
                        top: windowHeight - (targetBannerAdWidth / 16) * 9,// 根据系统约定尺寸计算出广告高度
                        left: (windowWidth - targetBannerAdWidth) / 5,
                    }
                });
                //banner.style.left = (windowWidth - targetBannerAdWidth) / 2;
                banner.onError(function (res) {
                    console.log('banner, ', res);
                });
                this._bannerAds[i] = banner;
            }
        }
    },

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }
        const isToutiaio = tt.getSystemInfoSync().appName === "Toutiao";
        if (!curMod._isAndroid) {
            return;
        }
        // 插屏广告仅今日头条安卓客户端支持
        if (isToutiaio) {
            const interstitialAd = tt.createInterstitialAd({
                adUnitId: curMod.InterstitialAdId
            });
            interstitialAd
                .load()
                .then(() => {
                    interstitialAd.show();
                })
                .catch(err => {
                    console.log(err);
                });
        }
    },

    craetTTRecorder() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        this.state = 0;
        this.RecorderManager = tt.getGameRecorderManager();
        //录屏开始
        this.RecorderManager.onStart(res => {
            console.log('录屏开始');
            var url = "lank_ico/TTvideo1";
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().VideoShareShow(false);
            require('GameMgr').Instance().SetVTimer();
            this.state = 1;
        });
        this.RecorderManager.onStop(res => {
            console.log(res.videoPath);
            console.log('录屏结束');
            //var url = "lank_ico/TTvideo0";
            //if (require('GameMgr').Instance().getLogin().screenBan) {
            var url = "lank_ico/videoStart";
            //}
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().stopVTimer();
            this.videoPath = res.videoPath;
            if (this.videoPath) {
                require('GameMgr').Instance().VideoShareShow(true);
            }
            this.state = 0;
        });
    },

    TTShareVideo() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (!this.videoPath) {
            return;
        }
        tt.shareAppMessage({
            channel: "video",
            title: "分享视频",
            desc: "分享精彩一刻",
            imageUrl: "",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: this.videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["录屏分享", "小游戏"]
            },
            success() {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频成功");
                if (require('GameMgr').Instance().getLogin().screenBan) {
                    return;
                }
                require('GameMgr').Instance().sendData("setScreenBan", { "screenBan": 1 }, function (data) {
                    if (data.code === 0) {
                        console.log("返回数据", data);
                        require('GameMgr').Instance().UnlockPet(19);
                        /*
                        require('GameMgr').Instance().showTip("分享成功！获得<img src='enjoy1'/> x 1", 0, "取消", "确定", function () {
                        }, function () {
                        });*/
                        require('GameMgr').Instance().setEnergy(1);
                        require('GameMgr').Instance().hidVideoBtn();
                    }
                    else {
                        console.log("连接失败", data);
                        return;
                    };
                });
            },
            fail(e) {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频失败", e);
                if (e.errMsg !== "shareAppMessage:cancel") {
                    require('GameMgr').Instance().showTip("分享视频失败,录制时间过短", 0, "取消", "确定", function () {
                    }, function () {
                    });
                }
            }
        });
    },

    TTRecorderCheck() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (this.state === 0) {
            this.RecorderManager.start({
                duration: 30,
            })
        }
        else if (this.state === 1) {
            this.RecorderManager.stop();
        }
    },

    createRewardedVideoAd(number) {
    },

    PYQshow() {
        tt.hideShareMenu();
    },

    PYQhid() {
        tt.hideShareMenu();
    },

    setLogin() {
        // let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (!window.wx) {
            return;
        }
        let self = this;

        wx.login({
            success(res) {
                console.log('请求登录');
                console.log(res)
                if (!res.isLogin) {
                    self.scheduleOnce(function () {
                        self.setLogin();
                    }, 0.5);
                }
                if (res.code) {
                    console.log('登录成功！')
                    console.log(res)
                    //发起网络请求
                    require('GameMgr').Instance().setresCode(res.code);
                    var id = require('GameMgr').Instance().ApiType;
                    console.log("渠道ID：" + id);

                    let self1 = self;
                    require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": id }, function (data) {
                        if (data.code === 0) {
                            console.log("返回数据", data);
                            require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                            //require('GameMgr').Instance().setGameStart();
                            self1.getWeiXinInfo();
                        }
                        else {
                            console.log("连接失败", data);
                            cc.director.loadScene('LoadScene');
                            return;
                        }
                    });

                    // cc.log(url);
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail(err) {
                console.log(err);
                console.log('再次登录');
                self.scheduleOnce(() => {
                    self.setLogin();
                }, 0.5);
            },
        })
    },

    /**
     * 获取微信信息
     */
    getWeiXinInfo() {
        let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (!isWeChat || !window.wx) {
            return;
        }
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        let self = this;

        tt.showShareMenu({
        });

        if (require('GameMgr').Instance().ApiType === 2) {
            wx.onShareAppMessage(function () {
                return {
                    title: curMod.ShareTitle,
                    imageUrlId: curMod.ShareImgId,
                    imageUrl: curMod.ShareImgUrl,
                }
            });
        }

        wx.onShow(function (para) {
            //console.log('onShow...' + JSON.stringify(para));
            if (require('GameMgr').Instance().ApiType === 2) {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                console.log("this.WatchVAD", this.WatchVAD);
                if (this.WatchVAD) {
                    require('GameMgr').Instance().ShowADrewords();
                    // 正常播放结束，可以下发游戏奖励
                    require('GameMgr').Instance().setDaily(2);
                }
            }
        });

        wx.onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });
        let sysInfo = window.wx.getSystemInfoSync();
        //获取微信界面大小
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;

        curMod._systemInfo = sysInfo;
        this.printInfo(sysInfo);

        window.wx.getSetting({
            success(res) {
                //console.log(res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    //console.log("用户已授权");
                    window.wx.getUserInfo({
                        success(res) {
                            //console.log(res);
                            curMod._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            console.log('curMod._wxUserInfo=' + JSON.stringify(curMod._wxUserInfo));
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            console.log(curMod._wxUserInfo);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetName(name);
                            require('GameMgr').Instance().setplUrl(imgurl);
                        }
                    });
                } else {
                    tt.openSetting();
                    tt.authorize({
                        scope: "scope.userInfo",
                        success(res) {
                            console.log("scope.userInfo", res);
                            curMod._wxUserInfo = res.userInfo;
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            console.log(curMod._wxUserInfo);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().SetName(name);
                            require('GameMgr').Instance().setplUrl(imgurl);
                        }
                    });
                }
            }
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)

        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});
